package com.example.springbootnacos.api;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class ApiServer {
    @NacosInjected
    private NamingService namingService;
    /**
     *
     */
    public String userServer="user";
    /**
     *
     */
    public String nacosServer="nacos-boot";
    /**
     * 根据serverName获取host+port
     * @param serverName
     * @return
     * @throws Exception
     */
    public String hostPort(String serverName) throws Exception{
        Instance instance = namingService.selectOneHealthyInstance(serverName);
        Optional.ofNullable(instance).orElseThrow(NullPointerException::new);
        String ip = instance.getIp();
        int port = instance.getPort();
        String hostPort = "http://" + ip + ":" + port;
        return hostPort;
    }

}
